﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using CLFramework.Utility;
using CLFramework.Windows.Forms;
using StockMonitor.Configuration;
using StockMonitor.Helper;

namespace StockMonitor.UserControls
{
    [ModuleContract("851CC365-12CA-4A6F-B041-9985D718D70D", "配置(&C)", "模型参数配置")]
    public partial class UCCapitalConfig : MdiUserControl
    {
        #region Ctor.

        public UCCapitalConfig()
            : base()
        {
            InitializeComponent();
        }

        public UCCapitalConfig(XmlNode node)
            : this()
        {
            InitializeComponent();
        }

        #endregion

        #region  MdiUserControl Members

        public override void Onload()
        {
            base.Onload();
            LoadMAConfig();
        }

        #endregion

        private void LoadMAConfig()
        {
            this.tbMAParams.Text = AppSettings.GetValue<string>("MAParams", "3|5|21", true);
            var maparam = this.tbMAParams.Text.Split('|').ToList();
            StringBuilder sb = new StringBuilder(string.Format("当前配置{0}条MA线，分别是:", maparam.Count));
            maparam.ForEach(m => { sb.Append(m); sb.Append("线 "); });
            this.lblCurrentMAParam.Text = sb.ToString();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (GlobalStatusContext.AutoTradeStarted)
            {
                MessageBox.Show("自动交易正在进行中，请先停止自动交易方可进行参数配置");
                return;
            }

            bool isValid = true; int temp;
            if (this.tbMAParams.Text.Trim().Split('|').Count() > 1)
            {
                this.tbMAParams.Text.Trim().Split('|').ToList().ForEach(s => isValid = (isValid && int.TryParse(s, out temp)));
            }
            else
                isValid = false;

            if (!isValid)
            {
                MessageBox.Show("参数输入错误，请检查您的输入格式");
            }
            else
            {
                AppSettings.SetValue("MAParams", this.tbMAParams.Text.Trim());
                MessageBox.Show("参数保存成功");

                LoadMAConfig();                
                Log.Info("保存MA参数成功，" + this.lblCurrentMAParam.Text);
            }
        }
    }
}
